/* eslint-disable @typescript-eslint/no-unused-vars */
import React from 'react';
import { Button, Col, message, Row, Select, Space, Spin, Switch } from 'antd';
import { ManListenCall, ManListenCallSession, TaskInfo } from 'seats/schema/Task';

import {
  closeListenCall,
  modifySeatBusy,
  modifySeatRest,
  modifySession,
  postHeart,
} from 'seats/servers/servers';
import { clearNull, filterDialogue, webDebug } from 'utils/tools';

import { getSocket } from 'servers/socket';
import { JSONObject } from 'seats/schema/common';
import { CallTaskInfoMsg, DiaogueMsg } from 'seats/schema/SocketMessage';
import ChatSeat from 'seats/pages/CallTask/Workspace/ChatSeat';
import HumanIntervention from 'seats/pages/CallTask/HumanIntervention';
import { ChatMessage } from 'seats/schema/ChatSeat';
import './style.scss';

import eventBus from 'utils/eventBus';
import {
  setAutoAnswer,
  setSeatRest,
  setScreenNum,
  setWorkspaceInfo,
  setSoundTemplateId,
  setManListenCallId,
} from '../../../../store/root/action';
import { connect } from 'react-redux';
import { sleep } from 'utils';
import { renderExceptionDom } from '../TaskTool';

/**示闲工作台 */
interface IState {
  /**
   * 弹屏下拉列表
   */
  screenOptions: any;
  /**
   * 模块页面数据
   */
  callInfo: ManListenCall;
  /**
   * 当前展示的聊天数据记录（根据弹屏数，最多5组）
   */
  currentRecord: ManListenCallSession[];
  /**
   * 右上方操作loading（网速慢，禁止其他操作）
   */
  headerLoading: boolean;
  /**
   * 退出任务loading
   */
  pageQuitLoading: boolean;
  /**
   * 人工介入 参数 callRecordId
   */
  callRecordIdHM: string;
  /**
   * 人工介入的callId
   */
  centerCallIdHM: string;
  /**
   * 人工介入类型 接听 或者人工介入
   */
  typeForHM: string;
  /**
   * 是否显示人工介入弹窗组件
   */
  showHumanDialog: boolean;
}

class Workspace extends React.Component<JSONObject, IState> {
  /**
   * 回话记录控件的引用集
   */
  private refGroup: React.RefObject<any>[];

  /**
   * 人工计入子组件
   */
  private hmRef: React.RefObject<any>;

  /**
   * sip推送实例列表 手续手动answer
   */
  private zrgEvt: any[];

  /**心跳计时器 */
  private timer: any;

  /**计时器执行次数 */
  private count: number;

  /**【自动接听】触发场景：
   * ①自动接听暂停时，FS消息通知会触发1次；
   * ②返回工作台有排队则触发，无排队暂停；
   * ③打开自动接听开关会触发1次 */
  /**自动接听进行中：true-排队自动【接听中】锁定，false-自动接听【暂停】 */
  private isAnswering: boolean;
  /**任务暂停，禁呼，完成，退出提示信息 */
  private taskQuitType?: string;
  /**自动退出任务执行中 */
  private isAutoQuit: boolean;

  /**
   * 聊天缓存
   * 在实际业务中，可能会同时有很多呼叫/通话，但是界面上只有两个聊天回话窗口，记录一个缓存将收到的但是不能渲染到界面的会话消息保存起来，已保证切换聊天窗口后信息的完整度
   */
  private chatCache: Map<string, ChatMessage[]> = new Map();
  constructor(prop: {}) {
    super(prop);
    // 初始化设置弹屏box窗口
    this.refGroup = [];
    this.hmRef = React.createRef();
    this.timer = undefined;
    this.count = 0;
    this.zrgEvt = [];
    this.isAnswering = false;
    this.taskQuitType = undefined;
    this.isAutoQuit = false;
    this.state = {
      screenOptions: [],
      callInfo: {} as CallTaskInfoMsg,
      currentRecord: [],
      headerLoading: false,
      pageQuitLoading: false,
      callRecordIdHM: '',
      centerCallIdHM: '',
      typeForHM: '',
      showHumanDialog: false,
    };
    this.hideHmDialog = this.hideHmDialog.bind(this);
    this.handleQuitTask = this.handleQuitTask.bind(this);
  }

  componentDidMount() {
    console.log('『「『「『「『「『「『工作台-页面========加载');
    const time = new Date().toLocaleTimeString();
    console.log('人机工作台-work-心跳****启动>>>>>>>>>>', time);
    this.startTimer();
    // 初始socket
    this.addSocketEvent();

    const options = this.initScreenOptions((this.props.taskInfo as TaskInfo)?.maxSeatsSession);
    this.setState({
      screenOptions: options,
    });

    eventBus.on('hideTransferPop', (callId: string) => {
      console.log('hideTransferPop===转人工【接听】长时间未接听或者被挂断，自动隐藏====', callId);
      const index = this.zrgEvt.findIndex(item => item.callId === callId);
      if (index > -1) {
        // 移除【接听】事件
        this.zrgEvt.splice(index, 1);
        console.log(
          '【*****重要调试信息*****】',
          callId,
          'hideTransferPop===长时间未接听，取消【接听】，更新【接听】排队',
          '=====this.zrgEvt===数组=====',
          this.showThisEvtArr()
        );

        const refGroup = this.refGroup;
        refGroup.length &&
          refGroup.forEach(ref => {
            if (ref.current?.getCenterCallId() === callId) {
              // 调用弹屏内部事件
              ref.current?.hideTransferPop();
            }
          });
      }
    });

    // 触发显示转人工按钮
    eventBus.on('showTransferPop', async (evt: JSONObject, callId: string) => {
      console.log('showTransferPop====保存转人工【接听】通话实例======', callId);
      const index = this.zrgEvt.findIndex(item => item.callId === callId);
      if (index < 0) {
        // 缓存【接听】事件，队尾
        this.zrgEvt.push({
          callId,
          evt,
        });
        console.log(
          '【*****重要调试信息*****】',
          callId,
          'showTransferPop===显示【接听】，更新【接听】排队',
          '=====this.zrgEvt===数组=====',
          this.showThisEvtArr()
        );

        const refGroup = this.refGroup;
        refGroup.length &&
          refGroup.forEach(ref => {
            if (ref.current?.getCenterCallId() === callId) {
              // 调用弹屏内部事件
              ref.current?.showTransferPop();
            }
          });
      }
      this.checkToAnswer(2);
    });

    // 触发人工监听关闭事件
    eventBus.on('closeManListenOk', (listenCallId: any) => {
      console.log('closeManListenOk===notice', listenCallId);
      const refGroup = this.refGroup;
      if (refGroup.length) {
        refGroup.forEach(ref => {
          if (ref.current?.getCenterCallId() === listenCallId) {
            console.group('%c%s', 'color:blue', '关闭【监听】的弹屏****', listenCallId);
            // 调用弹屏内部事件
            ref.current?.closeManListen();
            (this.props as JSONObject).setManListenCallId('');
            console.log(
              'overoveroveroveroveroverover监听的通话已挂断overoveroverover',
              listenCallId
            );
          }
        });
      }
    });
  }

  componentWillUnmount = () => {
    console.log('）））））））））））））））））工作台-页面卸载');
    this.clearTimer();

    eventBus.remove('hideTransferPop');
    eventBus.remove('showTransferPop');
    eventBus.remove('closeManListenOk');
    this.removeSocketEvent();
    this.setState = (state, callback) => {
      return;
    };
  };

  /**打印【接听】数组callId */
  showThisEvtArr() {
    const arr: any = [];
    this.zrgEvt.map(v => {
      return arr.push(v.callId);
    });
    return arr;
  }

  /**发送心跳 */
  async doHeart() {
    const time = new Date().toLocaleTimeString();
    // console.log('【人机】工作台-心跳******请求发送时间', time);
    try {
      const res = await postHeart();
      const newtime = new Date().toLocaleTimeString();
      // console.log('【人机】工作台-心跳>>>>>>>>返回code码', res.code, '****请求返回时间', newtime);
    } catch (error) {
      console.error(`系统异常: ${JSON.stringify(error)}`);
    }
  }

  /**开启定时器 */
  startTimer() {
    // console.log('人机工作台-work-心跳-次数', this.count);
    this.doHeart();
    this.count++;
    // 递归调用，避免用setInterval，长时间停留误差
    this.timer = setTimeout(() => {
      this.startTimer();
    }, 1000);
  }

  /**清除定时器 */
  clearTimer() {
    if (!this.timer) {
      return;
    }
    const time = new Date().toLocaleTimeString();
    // console.log('人机工作台-work-心跳****终止', time, this.timer);
    clearTimeout(this.timer);
    this.timer = null;
    this.count = 0;
  }

  /**
   * 请求修改弹屏数接口
   * 接口使用场景：示闲页面修改弹屏数
   * @param {number} [screenNum] 分屏数量，最大不超过创建任务时设置的最大值
   */
  async changeScreenNum(screenNum = 1) {
    const { taskId } = this.props.taskInfo;
    this.setState({
      headerLoading: true,
    });
    try {
      await modifySession(
        taskId,
        clearNull({
          seatsSession: screenNum,
        })
      );
      console.log('✅ 工作台-操作-切换弹屏数成功', screenNum);
      (this.props as JSONObject).setScreenNum(screenNum);
    } catch (error) {
      console.log('工作台-切换弹屏数-失败');
      console.error(`系统异常: ${JSON.stringify(error)}`);
    }
    this.setState({
      headerLoading: false,
    });
  }

  /**
   *获取弹屏数下拉选项列表
   * @param {number} max 创建任务设置的最大弹屏数
   * @return {*}
   */
  private initScreenOptions(max: number) {
    max = max || 1;
    const arr = [];
    for (let i = 1; i <= max; i++) {
      arr.push({
        value: i,
      });
    }
    return arr;
  }

  /**自动退出任务：
   * 条件-非人机交互页面，工作台没有弹屏推送
   * 任务结束，任务暂停--当前通话结束推送一次
   * 任务禁呼--每秒1次 */
  autoQuitTask(type: string) {
    if (this.isAutoQuit) {
      console.log('正在进行自动退出，不能重复操作。。。。。');
      return;
    }
    const msgObj: JSONObject = {
      paused: '任务已被管理员暂停',
      forbid: '已到达任务禁呼时间',
      end: '任务已完成',
    };
    const { showHumanDialog, callInfo } = this.state;
    if (!showHumanDialog && !callInfo.sessions.length) {
      this.isAutoQuit = true;
      message.info(msgObj[type], 1);
      setTimeout(this.handleQuitTask, 1000);
    }
  }

  /**操作-退出任务 */
  private async handleQuitTask() {
    // 需要判断弹屏是否都为空，存在正在通话中的弹屏，不能退出任务
    if (this.state.currentRecord.length) {
      message.info('当前存在未结束的通话，通话结束后才能退出');
      return;
    }
    this.setState({
      pageQuitLoading: true,
    });
    const { taskId } = this.props.taskInfo as TaskInfo;
    if (!taskId) {
      this.setState({
        pageQuitLoading: false,
      });
      this.goBack();
      return;
    }
    try {
      // 关闭监听
      const listenCallId = this.props.manListenCallId;
      if (listenCallId) {
        await closeListenCall(listenCallId as string);
        console.log('$$$$$$$$$$$【工作台】$$$$$$$接口成功>>>人工监听通话-关闭======', listenCallId);
      }
      // 操作-请求示忙
      await modifySeatBusy(taskId);
      console.log('✅ 操作-退出任务(示忙成功)--close workspace');
      await sleep(1000);
      this.goBack();
    } catch (error) {
      console.error(`系统异常: ${JSON.stringify(error)}`);
    }
    this.setState({
      pageQuitLoading: false,
    });
  }

  /**清除缓存，回任务列表页面 */
  goBack() {
    // 恢复示闲工作台配置
    (this.props as JSONObject).setSoundTemplateId('');
    (this.props as JSONObject).setWorkspaceInfo({});
    (this.props as JSONObject).setAutoAnswer('off');
    (this.props as JSONObject).setSeatRest('off');
    (this.props as JSONObject).setScreenNum(1);
    (this.props as JSONObject).setManListenCallId('');
    const history = (this.props as JSONObject).history;
    // 回到任务列表
    history.replace('/webseats/seats/callTask');
  }

  /**跳转下一步-人工介入||转人工接听 */
  private goNext(callRecordId: any, centerCallId: any, typeForHM: any) {
    this.isAnswering = true; //  弹窗开启前，拦截自动接听事件，防止FS方式或者开关打开触发自动接听，影响正在进行的人工介入
    console.log('跳转下一步-人工介入===centerCallId', centerCallId);
    console.log('跳转下一步-人工介入===callRecordId', callRecordId);
    console.log('跳转下一步-人工介入===typeForHM', typeForHM);
    if (typeForHM === 'robot') {
      // 接听 answer
      const index = this.zrgEvt.findIndex(item => item.callId === centerCallId);
      if (index === -1) {
        console.log('本次自动接听====中止==3，原因：接听事件不存在');
        this.isAnswering = false;
        return;
      }
      const curEvt = this.zrgEvt[index];
      console.log(typeForHM, '当前【接听】事件：', curEvt);
      curEvt.evt.session.answer({
        mediaConstraints: { audio: true },
      });
      // 接听成功，更新存储实例
      this.zrgEvt.splice(index, 1);
      console.log(
        '【*****重要调试信息*****】',
        centerCallId,
        'goNext===answer接听成功，从队列移除，更新【接听】排队',
        '=====this.zrgEvt===数组=====',
        this.showThisEvtArr()
      );
      console.log('=======================================================================');
      console.log('=======================================================================');
      console.log('*********************  ✅ 排队自动接听 ====成功 Success ✅ ****************');
      console.log('=======================================================================');
      console.log('=======================================================================');
    }
    this.setState({
      showHumanDialog: true,
      callRecordIdHM: callRecordId,
      centerCallIdHM: centerCallId,
      typeForHM: typeForHM,
    });
  }

  /**
   * 隐藏人工介入、转人工弹窗
   */
  hideHmDialog() {
    const { typeForHM, centerCallIdHM } = this.state;
    console.log('执行hideHmDialog*****隐藏弹窗', typeForHM, centerCallIdHM);
    console.log(
      '【*****重要调试信息*****】',
      '关闭弹窗后，当前【接听】排队情况',
      '=====this.zrgEvt===数组=====',
      this.showThisEvtArr()
    );
    this.setState(
      {
        showHumanDialog: false,
        callRecordIdHM: '',
        centerCallIdHM: '',
        typeForHM: '',
      },
      async () => {
        const { taskQuitType } = this;
        if (taskQuitType) {
          this.autoQuitTask(taskQuitType);
          return;
        }
        // 返回示闲工作台，自动转人工开启时，则判断是否存在排队
        // 2s后播放语音
        await sleep(2000);
        if (this.props.autoAnswer === 'on' && this.zrgEvt.length && !this.state.showHumanDialog) {
          // 1-有排队，自动接听最长等待
          console.log('转人工弹窗关闭，自动转人工开启====>>>>【自动转人工】排队中==============');
          message.info('正在接听其他排队客户', 1);
          const audio = new Audio('/webapp/waitingTransfer.wav');
          // 播放提示音，时长2s
          audio.play();
          audio.onended = () => {
            console.log('语音播放结束****');
            console.log('音乐时长', audio.duration);
          };
          // 语音播放时长需2s，完毕后【接听】
          await sleep(2000);
          this.isAnswering = false;
          this.checkToAnswer(3);
        } else {
          // 2-无排队，放开接听，可FS触发
          this.isAnswering = false;
        }
      }
    );
  }

  /**
   *操作-小休
   * on 开启小休 off 取消小休
   * 小休中，当前有对话的继续，不再推送新的对话，退出任务，结束示闲
   * 恢复后，继续推送新的对话
   */
  private handleSeatRest = async () => {
    this.setState({
      headerLoading: true,
    });
    const { seatRest } = this.props;
    const state: 'on' | 'off' = seatRest === 'off' ? 'on' : 'off';
    try {
      await modifySeatRest({
        restSwitch: state,
      });
      message.success('操作成功');

      (this.props as JSONObject).setSeatRest(state);
    } catch (error) {
      if (seatRest === 'on') {
        message.info('恢复失败，请稍后尝试或退出任务');
      }
      console.error(`系统异常: ${JSON.stringify(error)}`);
    }
    this.setState({
      headerLoading: false,
    });
  };
  /**
   *操作-坐席自动接听【开启\关闭】
   *
   * @private
   * @memberof Workspace
   */
  private handleAutoAnswer = async () => {
    const { autoAnswer } = this.props;
    const newVal: any = autoAnswer === 'off' ? 'on' : 'off';
    (this.props as JSONObject).setAutoAnswer(newVal);
    if (newVal === 'on') {
      console.log('自动接听===开启成功');
      message.success('自动接听已开启');
      // 有排队立即接听
      await sleep(1000);
      this.checkToAnswer(1);
    } else {
      console.log('自动接听===关闭成功');
      message.success('自动接听已关闭');
    }
  };

  /**
   * 检查排队情况，自动接听等待时间最久的通话
   * @param {number} [type] 1-自动接听开关触发；2-FS消息响铃触发；3-人机交互（转人工和人工介入）弹窗关闭触发
   */
  private checkToAnswer(type: number) {
    if (this.isAnswering) {
      console.log('自动接听====中止返回===0，原因：正在进行中');
      return;
    }
    console.log(
      '接听触发类型===',
      type,
      '>>>>参考【1-自动接听开关触发；2-FS消息响铃触发；3-人机交互（转人工和人工介入）弹窗关闭触发】'
    );
    this.isAnswering = true;
    if (!this.state.showHumanDialog && this.props.autoAnswer === 'on') {
      // 逻辑：如果自动转人工过程，手动点击【转人工】【人工介入】，则手动操作优先
      // 手动操作【接听】【人工介入】，会优先手动操作流程。暂停本次【自动转人工】接听后续操作
      // 逻辑：手动操作后，弹窗肯定是开启的，所以下面的代码不会执行
      const arr = this.zrgEvt;
      const refGroup = this.refGroup;
      if (arr.length && refGroup.length) {
        const current_callId = arr[0].callId;
        // 当前弹屏中查找，排队接听第一个元素（最早排队的通话）
        refGroup.forEach(ref => {
          if (ref.current?.getCenterCallId() === current_callId) {
            // 调用弹屏内部接听事件
            console.log('本次自动接听===操作接听事件=====即将【接听】的弹屏****', current_callId);
            ref.current?.handleContactMan();
          }
        });
      } else {
        console.log('本次自动接听====结束===1，原因：不存在【接听】排队');
        this.isAnswering = false;
      }
    } else {
      console.log('本次自动接听====结束===2，原因：手动操作影响，弹窗已经开启，或者自动接听未开启');
      this.isAnswering = false;
    }
  }

  /**
   * 绑定socket事件
   * dialogueContentEvent： 获取单句会话消息，渲染至页面
   * callTaskStatusEvent： 获取当前机器人正在 呼叫/通话 的列表并渲染
   */
  private addSocketEvent() {
    console.log('示闲工作台***通话推送-事件-start');
    const socket = getSocket();
    // 事件-任务状态
    socket.addEvent('callTaskStatusEvent', (data: JSONObject) => {
      // 任务Id
      const currentId = this.props.taskInfo?.taskId;
      const { screenNum } = this.props;
      // 查找当前任务id对应的socket信息
      if (data.taskId !== currentId?.toString()) {
        return;
      }
      console.log('示闲工作台-当前任务推送数据', data);
      this.hmRef.current && this.hmRef.current.onReceiveTaskStatusMsg(data);
      // 存储当前任务的推送信息
      const newRecords = [...data.sessions];
      const count = newRecords.length;
      // 当count为0时，说明当前没有正在进行的通话
      if (count) {
        // 根据sessions创建chartRef
        this.refGroup = [];
        for (let j = 0; j < count; j++) {
          // session中出现的通话记录条数，添加ref
          const chatRef_j = React.createRef<any>();
          this.refGroup.push(chatRef_j);
        }
        // sessions不足弹屏数时，补齐{}，凑齐弹屏展示
        for (let i = 0; i < screenNum - count; i++) {
          newRecords.push({});
        }
      }
      // 对应newRecords个数，弹屏初始化
      this.setState(
        {
          callInfo: data as CallTaskInfoMsg,
          currentRecord: newRecords,
        },
        () => {
          // state设置成功后，接收信息马上显示在界面
          // console.log('currentRecord====', this.state.currentRecord);
          // 任务自动退出检测
          const type = data.eventType;
          // 任务被暂停、到禁呼时间、任务结束，示闲工作台界面需要自动退出任务
          // socket推送，只推一次，任务结束，任务暂停；任务禁呼一直推送
          if (type === 'paused' || type === 'end' || type === 'forbid') {
            // 当前状态非禁呼时，收到推送，会自动执行退出
            // 防止禁呼推送，执行多次退出
            this.autoQuitTask(type);
            this.taskQuitType = type;
          } else {
            this.taskQuitType = undefined;
          }
        }
      );
    });
    // 事件-接收聊天记录消息
    socket.addEvent('dialogueContentEvent', (data: JSONObject) => {
      this.onReceiveMsg(data as DiaogueMsg);
      const { callRecordIdHM } = this.state;
      if (data.callRecordId === callRecordIdHM) {
        // 只传入人工介入或者转人工接听组件相关的会话
        this.hmRef.current && this.hmRef.current.onReceiveMsg(data);
      }
    });
  }

  /** 卸载socket事件*/
  removeSocketEvent() {
    console.log('示闲工作台->>>>socket事件-删除');
    const socket = getSocket();
    socket.removeEvent(['callTaskStatusEvent', 'dialogueContentEvent']);
  }

  /**
   * 收到会话的socket消息后，将数据处理一遍格式，转为Chat组件接受的数据格式，渲染会话消息并记录到缓存中
   */
  private onReceiveMsg(data: DiaogueMsg) {
    // 缓存聊天信息
    const cache = this.chatCache;
    const callRecordId = (data as DiaogueMsg).callRecordId;
    const record = cache.get(callRecordId) || [];
    const speakerMap = {
      '0': 'called',
      '1': 'caller',
      '2': 'man',
    };
    // index为0是开场语
    record.push({
      index: data.index,
      role: speakerMap[data.speaker as '0' | '1' | '2'] as 'called' | 'caller' | 'man',
      message: data.content,
      sound: data.url,
      status: data.status,
    });
    // 通话记录拼接后，需要根据index去重
    const newRecord = filterDialogue(record as ChatMessage[]);
    // 根据callRecordId，存储会话记录
    cache.set(callRecordId, newRecord);
    this.showOnScreenBox(callRecordId, newRecord);
  }

  /**根据callRecordId去refGroup中查找对应哪个弹屏，然后数据上屏展示 */
  private showOnScreenBox(callRecordId: string, record: any) {
    const refGroup = this.refGroup;
    if (refGroup.length) {
      refGroup.forEach((ref, index) => {
        // 目标元素：根据callRecordId在聊天记录中查找过滤
        if (ref.current?.getCallRecordId() === callRecordId) {
          ref.current?.setRecord(record);
          // 检测到record是否有开场语（index为0的记录），如果没有则打印日志，方便排查
          // if (record[0].index !== 0) {
          //   const phoneNum = ref.current?.getPhone();
          //   const centerCallId = ref.current?.getCenterCallId();
          //   console.log(
          //     '【弹屏-实时聊天数据更新】以下弹屏，聊天没有开场语（index为0缺失）❌❌❌❌❌❌❌ ***(注意：刷新工作台缓存会清除)',
          //     phoneNum,
          //     centerCallId,
          //     callRecordId
          //   );
          // }
        }
      });
    }
  }

  /**
   * 根据callRecordId获得一段对话
   */
  private getChatMsg(callRecordId: string): ChatMessage[] {
    return this.chatCache.get(callRecordId) || [];
  }

  /**
   * Chat组件点击查看历史后，将历史会话信息填入缓存中
   */
  private onGetHistory(msg: ChatMessage[], callRecordId: string): void {
    // 历史信息存入缓存
    this.chatCache.set(callRecordId, msg);
    // 更新屏幕聊天记录
    this.showOnScreenBox(callRecordId, msg);
  }

  render() {
    const {
      callInfo,
      currentRecord,
      screenOptions,
      headerLoading,
      pageQuitLoading,
      callRecordIdHM,
      centerCallIdHM,
      typeForHM,
      showHumanDialog,
    } = this.state;

    const { taskInfo, autoAnswer, seatRest, screenNum } = this.props;

    return (
      <>
        <div className="common-full-page workspace-page">
          <Spin spinning={pageQuitLoading} size="large">
            <div className="header">
              <Spin spinning={headerLoading} tip="加载中">
                <Row>
                  <Col flex="3" className="title">
                    <span>
                      {webDebug && <b className="debug-style">【{taskInfo?.taskId}】</b>}当前任务：
                      {taskInfo?.taskName}
                    </span>
                    <span>
                      任务进度：
                      {callInfo?.countComplete || taskInfo.finishedTaskNum} /
                      {taskInfo.totalTaskNum || 0}
                    </span>
                    <span>当前坐席组：{taskInfo.seatsGroupName}</span>
                  </Col>
                  <Col flex="2">
                    <Space style={{ float: 'right' }}>
                      <span className="font">转人工自动接听：</span>
                      <Switch checked={autoAnswer === 'on'} onChange={this.handleAutoAnswer} />
                      {seatRest === 'off' && (
                        <>
                          <span className="font">弹屏数设置：</span>
                          <Select
                            value={screenNum}
                            style={{ width: 120, marginRight: 10 }}
                            options={screenOptions}
                            onChange={val => {
                              // 改变弹屏数，根据新弹屏数示闲任务
                              this.changeScreenNum(val);
                            }}
                          />
                        </>
                      )}
                      <Button
                        onClick={this.handleSeatRest}
                        type="primary"
                        style={{ marginRight: 8 }}
                      >
                        {seatRest === 'on' ? '恢复' : '小休'}
                      </Button>
                      <Button onClick={this.handleQuitTask}>退出任务</Button>
                    </Space>
                  </Col>
                </Row>
              </Spin>
            </div>
            <div className="body">
              {callInfo.taskId && currentRecord.length > 0 ? (
                <Row className="box-row" justify="center" align="top">
                  {currentRecord.map((chatInfo, index) => (
                    // 通话记录-循环展示
                    <Col
                      className="box"
                      flex="1 1 0"
                      key={chatInfo.callId ? 'box_' + chatInfo.callId : 'box_' + index}
                    >
                      <div className="box-cont">
                        {/* 接通,有会话内容则显示 */}
                        {chatInfo.callRecordId && (
                          <ChatSeat
                            key={chatInfo.callRecordId}
                            showHistoryLink={true}
                            ref={this.refGroup[index]}
                            callSerialNumber={chatInfo.callSerialNumber}
                            callRecordId={chatInfo.callRecordId}
                            centerCallId={chatInfo.callId}
                            phoneNum={chatInfo.number}
                            status={chatInfo.state}
                            callTime={chatInfo.inviteTime}
                            messages={this.getChatMsg(chatInfo.callRecordId)}
                            onGetHistory={this.onGetHistory.bind(this)}
                            goNext={this.goNext.bind(this)}
                          />
                        )}
                        {/* 无通话内容 */}
                        {!chatInfo.callRecordId && renderExceptionDom(callInfo, seatRest)}
                      </div>
                    </Col>
                  ))}
                </Row>
              ) : (
                renderExceptionDom(callInfo, seatRest)
              )}
            </div>
          </Spin>
        </div>
        {/*人工介入弹窗组件*/}
        <HumanIntervention
          showHumanDialog={showHumanDialog}
          callRecordId={callRecordIdHM}
          centerCallId={centerCallIdHM}
          type={typeForHM}
          ref={this.hmRef}
          history={(this.props as any).history}
          onHideHmDialog={this.hideHmDialog}
        />
      </>
    );
  }
}

// state 注入props
const mapStateToProps = (state: JSONObject) => {
  return {
    taskInfo: state.workspaceInfo,
    autoAnswer: state.autoAnswer,
    seatRest: state.seatRest,
    screenNum: state.screenNum,
    soundTemplateId: state.soundTemplateId,
    manListenCallId: state.manListenCallId,
  };
};
// action 注入props
const mapDispatchToProps = {
  setAutoAnswer,
  setSeatRest,
  setScreenNum,
  setWorkspaceInfo,
  setSoundTemplateId,
  setManListenCallId,
};

export default connect(mapStateToProps, mapDispatchToProps)(Workspace);
